from rest_framework import viewsets, status
from rest_framework.response import Response
from rest_framework.decorators import action
from django.db.models import Q, F, ExpressionWrapper, DateField
from rest_framework.pagination import PageNumberPagination
import datetime
import pandas as pd
from io import BytesIO
import json
import logging
from django.http import HttpResponse

from ..models import Order
from ..serializers import OrderListSerializer
from rest_framework import serializers

# 获取logger对象
logger = logging.getLogger(__name__)

class ExpirationSerializer(OrderListSerializer):
    """扩展OrderListSerializer，添加到期日期字段"""
    expiration_date = serializers.SerializerMethodField()
    
    def get_expiration_date(self, obj):
        """计算到期日期"""
        if obj.activation_date and obj.purchase_years > 0:
            return obj.activation_date + datetime.timedelta(days=365 * obj.purchase_years)
        return None

class CustomPagination(PageNumberPagination):
    """自定义分页类，支持page_size参数"""
    page_size = 10
    page_size_query_param = 'page_size'
    max_page_size = 100

class ExpirationViewSet(viewsets.ReadOnlyModelViewSet):
    """产品授权到期表视图集"""
    serializer_class = ExpirationSerializer
    pagination_class = CustomPagination
    
    def get_queryset(self):
        """获取非永久授权且已激活的订单，且到期日期小于等于今天日期"""
        today = datetime.date.today()
        
        # 获取查询参数
        month = self.request.query_params.get('month', None)
        expiration_date_start = self.request.query_params.get('expiration_date_start', None)
        expiration_date_end = self.request.query_params.get('expiration_date_end', None)
        product_id = self.request.query_params.get('product_id', None)
        ordering = self.request.query_params.get('ordering', 'days_to_expiration')  # 默认按到期日期接近度排序
        
        # 基础查询：非永久授权、已激活
        queryset = Order.objects.filter(
            purchase_years__gt=0,  # 非永久授权
            order_status=1,  # 已激活
            activation_date__isnull=False  # 有激活日期
        )
        
        # 记录查询参数
        logger.info(f"查询参数: 月份={month}, 日期范围={expiration_date_start}至{expiration_date_end}, 产品ID={product_id}, 排序={ordering}")
        logger.info(f"基础查询结果数: {queryset.count()}")
        
        # 所有满足条件的订单
        all_orders = list(queryset)
        
        # 筛选符合条件的订单（到期日期小于等于今天日期）并添加到期日期属性
        expiring_orders = []
        for order in all_orders:
            # 计算到期日期
            if order.activation_date:
                exp_date = order.activation_date + datetime.timedelta(days=365 * order.purchase_years)
                # 添加到期日期属性
                order.expiration_date = exp_date
                
                # 计算与今天的天数差（用于排序）
                order.days_to_expiration = (exp_date - today).days
                
                if exp_date <= today:  # 到期日期小于等于今天日期
                    expiring_orders.append(order)
        
        logger.info(f"到期订单数: {len(expiring_orders)}")
        
        # 过滤特定月份的到期订单（保留旧逻辑兼容性）
        if month:
            # 解析月份 (格式: YYYY-MM)
            try:
                year, month = map(int, month.split('-'))
                # 计算该月的开始和结束日期
                start_date = datetime.date(year, month, 1)
                if month == 12:
                    end_date = datetime.date(year + 1, 1, 1) - datetime.timedelta(days=1)
                else:
                    end_date = datetime.date(year, month + 1, 1) - datetime.timedelta(days=1)
                
                # 过滤该月到期的订单
                month_expiring_orders = []
                for order in expiring_orders:
                    # 计算到期日期
                    if start_date <= order.expiration_date <= end_date:
                        month_expiring_orders.append(order)
                
                expiring_orders = month_expiring_orders
                logger.info(f"指定月份{year}-{month}到期订单数: {len(expiring_orders)}")
            except ValueError:
                logger.error(f"月份格式不正确: {month}")
                pass
        
        # 按日期范围筛选（新增功能）
        if expiration_date_start or expiration_date_end:
            filtered_by_date_range = []
            
            try:
                start_date = None
                if expiration_date_start:
                    start_date = datetime.datetime.strptime(expiration_date_start, "%Y-%m-%d").date()
                
                end_date = None
                if expiration_date_end:
                    end_date = datetime.datetime.strptime(expiration_date_end, "%Y-%m-%d").date()
                
                for order in expiring_orders:
                    if start_date and order.expiration_date < start_date:
                        continue
                    if end_date and order.expiration_date > end_date:
                        continue
                    filtered_by_date_range.append(order)
                
                expiring_orders = filtered_by_date_range
                logger.info(f"日期范围筛选后的订单数: {len(expiring_orders)}")
            except ValueError as e:
                logger.error(f"日期格式不正确: {str(e)}")
        
        # 过滤特定产品
        if product_id:
            expiring_orders = [order for order in expiring_orders if str(order.product_name.id) == str(product_id)]
            logger.info(f"指定产品ID={product_id}到期订单数: {len(expiring_orders)}")
        
        # 排序
        if ordering:
            reverse = False
            sort_field = ordering
            
            if ordering.startswith('-'):
                reverse = True
                sort_field = ordering[1:]
            
            if sort_field == 'days_to_expiration':
                # 按接近到期日期排序（天数少的排前面）
                expiring_orders.sort(key=lambda x: x.days_to_expiration)
            elif sort_field == 'expiration_date':
                expiring_orders.sort(key=lambda x: x.expiration_date, reverse=reverse)
            elif hasattr(Order, sort_field):
                expiring_orders.sort(key=lambda x: getattr(x, sort_field, None), reverse=reverse)
        
        # 确保结果是查询集而不是列表，这样才能支持分页
        order_ids = [order.id for order in expiring_orders]
        logger.info(f"最终过滤后的订单数: {len(order_ids)}")
        return Order.objects.filter(id__in=order_ids)
    
    def list(self, request, *args, **kwargs):
        """重写list方法，确保正确处理分页和排序"""
        logger.info("进入list方法")
        logger.info(f"请求参数: {request.query_params}")
        
        queryset = self.get_queryset()
        
        # 获取查询参数
        ordering = request.query_params.get('ordering', 'days_to_expiration')  # 默认按到期日期接近度排序
        page = request.query_params.get('page', '1')
        page_size = request.query_params.get('page_size', '10')
        
        logger.info(f"排序: {ordering}, 页码: {page}, 每页大小: {page_size}")
        
        # 计算所有订单的到期日期
        today = datetime.date.today()
        orders_list = []
        for order in queryset:
            if order.activation_date and order.purchase_years > 0:
                order.expiration_date = order.activation_date + datetime.timedelta(days=365 * order.purchase_years)
                # 计算与今天的天数差（用于按接近度排序）
                order.days_to_expiration = (order.expiration_date - today).days
            else:
                order.expiration_date = None
                order.days_to_expiration = float('inf')  # 无到期日期的排在最后
            orders_list.append(order)
        
        # 内存中排序
        if ordering:
            reverse = False
            sort_field = ordering
            
            if ordering.startswith('-'):
                reverse = True
                sort_field = ordering[1:]
            
            if sort_field == 'days_to_expiration':
                # 按接近到期日期排序（天数少的排前面）
                if reverse:
                    # 降序：远的排前面
                    orders_list.sort(key=lambda x: x.days_to_expiration, reverse=True)
                else:
                    # 升序：近的排前面
                    orders_list.sort(key=lambda x: x.days_to_expiration)
            elif sort_field == 'expiration_date':
                # 按到期日期排序
                orders_list.sort(key=lambda x: x.expiration_date if x.expiration_date else datetime.date.max, reverse=reverse)
            elif hasattr(Order, sort_field):
                orders_list.sort(key=lambda x: getattr(x, sort_field, None), reverse=reverse)
        
        # 订单总数
        total_count = len(orders_list)
        logger.info(f"总订单数: {total_count}")
        
        # 手动分页
        try:
            page = int(page)
            page_size = int(page_size)
        except ValueError:
            page = 1
            page_size = 10
            logger.error(f"分页参数转换错误，使用默认值: page={page}, page_size={page_size}")
        
        # 计算起始和结束索引
        start_idx = (page - 1) * page_size
        end_idx = min(start_idx + page_size, total_count)
        
        # 获取当前页的数据
        paginated_orders = orders_list[start_idx:end_idx]
        logger.info(f"当前页数据范围: {start_idx}-{end_idx}, 数据条数: {len(paginated_orders)}")
        
        # 序列化数据
        serializer = self.get_serializer(paginated_orders, many=True)
        
        # 构建分页响应
        next_url = None if end_idx >= total_count else f'?page={page+1}&page_size={page_size}'
        previous_url = None if page <= 1 else f'?page={page-1}&page_size={page_size}'
        
        response_data = {
            'code': 200,
            'message': '获取到期订单列表成功',
            'data': {
                'count': total_count,
                'next': next_url,
                'previous': previous_url,
                'results': serializer.data
            }
        }
        
        # 记录响应数据
        logger.info(f"响应数据: count={total_count}, next={next_url}, previous={previous_url}, results_count={len(serializer.data)}")
        
        return Response(response_data)
    
    @action(detail=False, methods=['get'])
    def export(self, request):
        """导出到期数据为Excel"""
        logger.info(f"开始导出到期数据，查询参数: {request.query_params}")
        
        try:
            # 使用与筛选相同的逻辑获取查询集
            queryset = self.get_queryset()
            
            # 计算到期日期并创建在内存中的完整结果集
            today = datetime.date.today()
            orders_with_exp_dates = []
            for order in queryset:
                if order.activation_date and order.purchase_years > 0:
                    order.expiration_date = order.activation_date + datetime.timedelta(days=365 * order.purchase_years)
                    # 计算与今天的天数差（用于按接近度排序）
                    order.days_to_expiration = (order.expiration_date - today).days
                else:
                    order.expiration_date = None
                    order.days_to_expiration = float('inf')  # 无到期日期的排在最后
                orders_with_exp_dates.append(order)
                
            # 根据排序参数排序（与list方法相同的逻辑）
            ordering = request.query_params.get('ordering', 'days_to_expiration')
            if ordering:
                reverse = False
                sort_field = ordering
                
                if ordering.startswith('-'):
                    reverse = True
                    sort_field = ordering[1:]
                
                if sort_field == 'days_to_expiration':
                    # 按接近到期日期排序（天数少的排前面）
                    if reverse:
                        # 降序：远的排前面
                        orders_with_exp_dates.sort(key=lambda x: x.days_to_expiration, reverse=True)
                    else:
                        # 升序：近的排前面
                        orders_with_exp_dates.sort(key=lambda x: x.days_to_expiration)
                elif sort_field == 'expiration_date':
                    # 按到期日期排序
                    orders_with_exp_dates.sort(key=lambda x: x.expiration_date if x.expiration_date else datetime.date.max, reverse=reverse)
                elif hasattr(Order, sort_field):
                    orders_with_exp_dates.sort(key=lambda x: getattr(x, sort_field, None), reverse=reverse)
            
            logger.info(f"准备导出 {len(orders_with_exp_dates)} 条记录")
            
            # 创建一个空的DataFrame
            df = pd.DataFrame()
            
            if not orders_with_exp_dates:
                # 如果没有数据，创建一个只有列标题的DataFrame
                df = pd.DataFrame(columns=[
                    '到期月份', '到期日期', '到期产品', '订单号', '客户名称', 
                    '授权域名', '下单日期', '购买年限', '激活日期', '激活人',
                    '激活状态', '订单金额'
                ])
                logger.warning("导出的数据为空，将只包含列标题")
            else:
                # 计算到期月份和到期日期
                expiration_months = []
                expiration_dates = []
                for order in orders_with_exp_dates:
                    if hasattr(order, 'expiration_date') and order.expiration_date:
                        exp_date = order.expiration_date
                        expiration_dates.append(exp_date)
                        expiration_months.append(exp_date.strftime('%Y-%m'))
                    else:
                        expiration_dates.append(None)
                        expiration_months.append('-')
                
                # 添加所需列
                df['到期月份'] = expiration_months
                df['到期日期'] = expiration_dates
                df['到期产品'] = [order.product_name.product_name if order.product_name else '-' for order in orders_with_exp_dates]
                df['订单号'] = [order.order_number for order in orders_with_exp_dates]
                df['客户名称'] = [order.customer_name.customer_name if order.customer_name else '-' for order in orders_with_exp_dates]
                df['授权域名'] = [order.authorized_domain or '-' for order in orders_with_exp_dates]
                df['下单日期'] = [order.order_date for order in orders_with_exp_dates]
                df['购买年限'] = [order.get_purchase_years_display() for order in orders_with_exp_dates]
                df['激活日期'] = [order.activation_date for order in orders_with_exp_dates]
                df['激活人'] = [order.nickname.nickname if order.nickname else '-' for order in orders_with_exp_dates]
                df['激活状态'] = [order.get_order_status_display() for order in orders_with_exp_dates]
                df['订单金额'] = [order.order_amount for order in orders_with_exp_dates]
            
            # 创建一个字节流
            output = BytesIO()
            
            # 将DataFrame写入Excel
            try:
                with pd.ExcelWriter(output, engine='xlsxwriter') as writer:
                    df.to_excel(writer, sheet_name='到期数据', index=False)
                    
                    # 获取XlsxWriter对象并添加格式
                    workbook = writer.book
                    worksheet = writer.sheets['到期数据']
                    
                    # 设置列宽
                    for i, col in enumerate(df.columns):
                        # 获取列中最长字符串的长度
                        max_len = max(df[col].astype(str).map(len).max(), len(col)) + 2
                        # 设置列宽
                        worksheet.set_column(i, i, max_len)
                        
                    # 添加一个说明工作表
                    info_sheet = workbook.add_worksheet('说明')
                    bold_format = workbook.add_format({'bold': True})
                    
                    # 写入说明信息
                    info_sheet.write(0, 0, '产品到期数据导出说明', bold_format)
                    info_sheet.write(1, 0, '1. 数据是根据当前筛选条件导出的')
                    info_sheet.write(2, 0, '2. 到期日期 = 激活日期 + 购买年限')
                    info_sheet.write(3, 0, '3. 导出时间: ' + datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
                    
                    # 设置第一列宽度
                    info_sheet.set_column(0, 0, 50)
                    
                logger.info("Excel文件已成功写入内存")
            except Exception as excel_error:
                logger.error(f"写入Excel文件失败: {str(excel_error)}", exc_info=True)
                return Response({
                    'code': 500,
                    'message': f'写入Excel文件失败: {str(excel_error)}',
                    'data': None
                }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
            
            # 设置文件指针到开始
            output.seek(0)
            
            # 创建响应
            try:
                file_data = output.getvalue()
                logger.info(f"Excel文件大小: {len(file_data)} 字节")
                
                # 生成文件名，包含当前日期时间
                current_time = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
                filename = f'产品到期数据_{current_time}.xlsx'
                
                response = HttpResponse(
                    file_data,
                    content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
                )
                response['Content-Disposition'] = f'attachment; filename="{filename}"'
                response['Content-Length'] = len(file_data)
                
                logger.info(f"成功创建Excel响应: {filename}")
                return response
            except Exception as response_error:
                logger.error(f"创建HTTP响应失败: {str(response_error)}", exc_info=True)
                return Response({
                    'code': 500,
                    'message': f'创建下载响应失败: {str(response_error)}',
                    'data': None
                }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
            
        except Exception as e:
            logger.error(f"导出到期数据失败: {str(e)}", exc_info=True)
            return Response({
                'code': 500,
                'message': f'导出到期数据失败: {str(e)}',
                'data': None
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    
    @action(detail=False, methods=['get'])
    def import_template(self, request):
        """获取导入模板"""
        logger.info("开始生成到期产品导入模板")
        
        try:
            # 使用pandas创建DataFrame
            import pandas as pd
            import openpyxl
            from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
            
            # 创建DataFrame并添加示例数据
            df = pd.DataFrame({
                '订单号*': ['ORD202401001'],
                '客户名称*': ['示例客户'],
                '产品名称*': ['Elementor Pro'],
                '授权域名*': ['example.com'],
                '订单金额*': [199.00],
                '购买年限*': [1],
                '激活日期*': ['2023-01-01'],
                '激活人': ['张三'],
                '订单备注': ['示例订单备注']
            })
            
            logger.info("已创建DataFrame并添加示例数据")
            
            # 创建一个字节流
            output = BytesIO()
            logger.info("已创建字节流")
            
            # 使用ExcelWriter写入到字节流
            with pd.ExcelWriter(output, engine='xlsxwriter') as writer:
                # 将DataFrame写入到Excel文件
                df.to_excel(writer, sheet_name='到期产品导入模板', index=False)
                logger.info("已将数据写入到Excel工作表")
                
                # 获取xlsxwriter工作簿和工作表对象
                workbook = writer.book
                worksheet = writer.sheets['到期产品导入模板']
                
                # 设置列宽
                for i, col in enumerate(df.columns):
                    max_width = max(df[col].astype(str).map(len).max(), len(col)) + 2
                    worksheet.set_column(i, i, max_width)
                logger.info("已设置列宽")
                
                # 添加说明工作表
                info_sheet = workbook.add_worksheet('使用说明')
                bold_format = workbook.add_format({'bold': True})
                
                info_sheet.write(0, 0, '说明：', bold_format)
                info_sheet.write(1, 0, '1. 带*的字段为必填项')
                info_sheet.write(2, 0, '2. 购买年限可填写：1, 2, 3, 4, 5 (对应年数)，或填写0表示永久授权')
                info_sheet.write(3, 0, '3. 日期格式：YYYY-MM-DD，例如2023-01-01')
                info_sheet.write(4, 0, '4. 导入时会自动计算到期日期 = 激活日期 + 购买年限')
                
                # 添加产品列表
                try:
                    from ..models import Product
                    products = Product.objects.all()
                    if products:
                        products_sheet = workbook.add_worksheet('产品列表')
                        products_sheet.write(0, 0, '可用产品列表（用于产品名称字段）', bold_format)
                        for idx, product in enumerate(products, 1):
                            products_sheet.write(idx, 0, product.product_name)
                        products_sheet.set_column(0, 0, 30)
                except Exception as e:
                    logger.error(f"获取产品列表失败: {str(e)}")
                
                # 获取用户列表
                try:
                    from apps.UMM.models import User
                    users = User.objects.filter(nickname__isnull=False)
                    if users:
                        users_sheet = workbook.add_worksheet('用户列表')
                        users_sheet.write(0, 0, '可用用户列表（用于激活人字段）', bold_format)
                        for idx, user in enumerate(users, 1):
                            if user.nickname:
                                users_sheet.write(idx, 0, user.nickname)
                        users_sheet.set_column(0, 0, 20)
                except Exception as e:
                    logger.error(f"获取用户列表失败: {str(e)}")
                
            # 将字节流指针移回起始位置
            output.seek(0)
            logger.info("已将字节流指针移回起始位置")
            
            # 获取字节流的值
            excel_data = output.getvalue()
            logger.info(f"Excel数据大小: {len(excel_data)} 字节")
            
            # 创建HTTP响应
            response = HttpResponse(
                excel_data,
                content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            )
            response['Content-Disposition'] = 'attachment; filename="产品到期数据导入模板.xlsx"'
            logger.info("已创建HTTP响应")
            
            # 关闭字节流
            output.close()
            logger.info("已关闭字节流")
            
            return response
            
        except Exception as e:
            logger.error(f"生成到期产品导入模板失败: {str(e)}", exc_info=True)
            return Response({
                'code': 500,
                'message': f'生成导入模板失败: {str(e)}',
                'data': None
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    
    @action(detail=False, methods=['post'])
    def import_data(self, request):
        """导入到期产品数据"""
        logger.info(f"接收到到期产品导入请求: {request.data}")
        logger.info(f"上传的文件: {request.FILES}")
        
        # 检查请求中是否有文件
        file = request.FILES.get('file')
        if not file:
            logger.error("未接收到文件")
            return Response({
                'code': 400,
                'message': '未提供文件',
                'data': None
            }, status=status.HTTP_400_BAD_REQUEST)
            
        # 检查文件类型
        if not (file.name.endswith('.xlsx') or file.name.endswith('.xls')):
            logger.error(f"文件格式不正确: {file.name}")
            return Response({
                'code': 400,
                'message': '只支持.xlsx或.xls格式的Excel文件',
                'data': None
            }, status=status.HTTP_400_BAD_REQUEST)
            
        try:
            import tempfile
            import os
            
            temp_file_path = None
            
            try:
                # 将上传的文件保存到临时目录
                with tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(file.name)[1]) as temp_file:
                    for chunk in file.chunks():
                        temp_file.write(chunk)
                    temp_file_path = temp_file.name
                
                logger.info(f"文件已保存到临时路径: {temp_file_path}")
                
                # 尝试使用pandas读取Excel文件
                try:
                    df = pd.read_excel(temp_file_path)
                    logger.info(f"成功读取Excel文件，共{len(df)}行数据")
                except Exception as excel_error:
                    logger.error(f"读取Excel文件失败: {str(excel_error)}")
                    return Response({
                        'code': 400,
                        'message': f'无法读取Excel文件: {str(excel_error)}',
                        'data': None
                    }, status=status.HTTP_400_BAD_REQUEST)
            finally:
                # 确保清理临时文件
                if temp_file_path and os.path.exists(temp_file_path):
                    try:
                        os.unlink(temp_file_path)
                        logger.info(f"已删除临时文件: {temp_file_path}")
                    except Exception as delete_error:
                        logger.warning(f"删除临时文件失败: {str(delete_error)}")
            
            # 检查数据是否为空
            if df.empty:
                logger.error("上传的Excel文件不包含任何数据")
                return Response({
                    'code': 400,
                    'message': '上传的Excel文件不包含任何数据',
                    'data': None
                }, status=status.HTTP_400_BAD_REQUEST)
            
            # 检查必填列是否存在
            required_columns = ['订单号', '客户名称', '产品名称', '授权域名', '订单金额', '购买年限', '激活日期']
            missing_columns = [col for col in required_columns if col.replace('*', '') not in df.columns]
            if missing_columns:
                logger.error(f"缺少必填列: {missing_columns}")
                return Response({
                    'code': 400,
                    'message': f'缺少必填列: {", ".join(missing_columns)}',
                    'data': None
                }, status=status.HTTP_400_BAD_REQUEST)
                    
            # 数据处理和导入
            from ..models import Order, Product, Customer
            from apps.UMM.models import User
            import datetime
            
            success_count = 0
            error_records = []
            
            for index, row in df.iterrows():
                try:
                    # 检查必填字段
                    empty_fields = []
                    for field in required_columns:
                        field_name = field.replace('*', '')
                        if pd.isna(row.get(field_name)):
                            empty_fields.append(field_name)
                    
                    if empty_fields:
                        error_records.append({
                            "row": index + 2,  # Excel行号从1开始，且有表头
                            "error": f"以下必填字段不能为空: {', '.join(empty_fields)}"
                        })
                        continue
                    
                    # 尝试转换数据类型
                    try:
                        purchase_years = int(row['购买年限'])
                        order_amount = float(row['订单金额'])
                    except (ValueError, TypeError) as type_error:
                        error_records.append({
                            "row": index + 2,
                            "error": f"数据类型错误: 购买年限必须为整数，订单金额必须为数字。详细错误: {str(type_error)}"
                        })
                        continue
                    
                    # 处理日期
                    try:
                        activation_date = pd.to_datetime(row['激活日期']).date()
                    except Exception as date_error:
                        error_records.append({
                            "row": index + 2,
                            "error": f"日期格式无效: {str(date_error)}"
                        })
                        continue
                    
                    # 处理产品
                    product_name = str(row['产品名称']).strip()
                    try:
                        product = Product.objects.get(product_name=product_name)
                    except Product.DoesNotExist:
                        error_records.append({
                            "row": index + 2,
                            "error": f"产品 '{product_name}' 不存在"
                        })
                        continue
                        
                    # 处理客户
                    customer_name = str(row['客户名称']).strip()
                    try:
                        customer = Customer.objects.get(customer_name=customer_name)
                    except Customer.DoesNotExist:
                        error_records.append({
                            "row": index + 2,
                            "error": f"客户 '{customer_name}' 不存在"
                        })
                        continue
                        
                    # 处理对接人
                    nickname = None
                    if not pd.isna(row.get('激活人', '')):
                        try:
                            nickname = User.objects.get(nickname=str(row['激活人']).strip())
                        except User.DoesNotExist:
                            error_records.append({
                                "row": index + 2,
                                "error": f"系统中不存在昵称为 '{row['激活人']}' 的用户"
                            })
                            continue
                    
                    # 检查订单号是否已存在
                    order_number = str(row['订单号']).strip()
                    if Order.objects.filter(order_number=order_number).exists():
                        error_records.append({
                            "row": index + 2,
                            "error": f"订单号 '{order_number}' 已存在"
                        })
                        continue
                    
                    # 创建订单
                    order = Order(
                        order_number=order_number,
                        customer_name=customer,
                        product_name=product,
                        authorized_domain=str(row['授权域名']).strip(),
                        order_amount=order_amount,
                        purchase_years=purchase_years,
                        activation_date=activation_date,
                        order_status=1,  # 已激活
                        order_date=datetime.date.today(),  # 设置为今天
                        nickname=nickname,
                        order_remarks=str(row.get('订单备注', '')) if not pd.isna(row.get('订单备注', '')) else ''
                    )
                    
                    # 保存订单
                    order.save()
                    success_count += 1
                    logger.info(f"成功导入第{index + 2}行数据，订单号: {order.order_number}")
                    
                except Exception as e:
                    logger.error(f"导入行 {index + 2} 失败: {str(e)}", exc_info=True)
                    error_records.append({
                        "row": index + 2,
                        "error": str(e)
                    })
                    
            # 返回导入结果
            result = {
                "success_count": success_count,
                "error_count": len(error_records),
                "errors": error_records
            }
            
            logger.info(f"导入结果: 成功={success_count}, 错误={len(error_records)}")
            
            if success_count > 0:
                return Response({
                    'code': 200,
                    'message': f'成功导入{success_count}条记录，失败{len(error_records)}条',
                    'data': result
                })
            else:
                return Response({
                    'code': 400,
                    'message': f'导入失败，共{len(error_records)}条错误记录',
                    'data': result
                }, status=status.HTTP_400_BAD_REQUEST)
                
        except Exception as e:
            logger.error(f"导入到期产品数据失败: {str(e)}", exc_info=True)
            return Response({
                'code': 500,
                'message': f'导入失败: {str(e)}',
                'data': None
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR) 